﻿#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent) :
    BaseEditor(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);

    table=PUNCH_2017;

    itemModel=new QStandardItemModel(this);
    ui->tableView->setModel(itemModel);
    ui->tableView->setEditTriggers(QTableView::NoEditTriggers);

    updateView();
    createMenu();
}

Widget::~Widget()
{
    delete ui;
}

void Widget::generateMenu()
{
    menu->addAction(QStringLiteral("统计出勤天数"),this,&Widget::updateDutyDays);
    menu->addAction(QStringLiteral("统计迟到次数"),this,&Widget::updateLateDays);
    menu->addSeparator();
    menu->addAction(QStringLiteral("显示图表[柱形图]"),this,&Widget::showBarChart);
    menu->addAction(QStringLiteral("显示图表[散点图]"),this,&Widget::showScatterChart);
    menu->addSeparator();
    menu->addAction(QStringLiteral("当前员工图表[折线图]"),this,&Widget::showLineChart);
}

void Widget::updatePunchTick()
{
    if(!staffs.isEmpty())
        staffs.clear();

    if(!punchTicks.isEmpty())
        punchTicks.clear();

    QSqlQuery query;
    query.exec(QString("select label,COUNT(label) as tick from %1 GROUP BY label")
               .arg(table));

    while (query.next()) {
        QString label=query.value("label").toString();
        int tick=query.value("tick").toInt();
        staffs.append(label);
        punchTicks.insert(label,tick);
    }

    if(!punchTicks.isEmpty())
    {
        foreach (QString staff, staffs) {
            QList<QStandardItem *> items;
            items.append(new QStandardItem(staff));
            items.append(new QStandardItem(QString::number(punchTicks.value(staff))));
            if(!items.isEmpty())
                itemModel->appendRow(items);
        }
        itemModel->setHeaderData(NAME_COL,Qt::Horizontal,QStringLiteral("姓名"));  //label
        itemModel->setHeaderData(PUNCH_COL,Qt::Horizontal,QStringLiteral("打卡数"));  //tick
    }
}

void Widget::updateSummary()
{
    QSqlQuery query;
    query.exec(QString("SELECT COUNT(label) from %1").arg(table));
    if(query.next())
    {
        QString total=query.value(0).toString();
        ui->summary->setText(QStringLiteral("当前记录数： ") + total);
    }
}

void Widget::updateView()
{
    itemModel->clear();

    updatePunchTick();
    updateSummary();
}

void Widget::updateDutyDays()
{
    if(staffs.isEmpty())
        return;

    if(!dutyDays.isEmpty())
        dutyDays.clear();

    if(itemModel->columnCount() > 1)
        itemModel->removeColumn(DUTY_COL);

    QSqlQuery query;
    foreach (QString staff, staffs) {
        query.exec(QString("select date_ from %1 where label='%2' GROUP BY date_")
                   .arg(table).arg(staff));
        if(query.isActive())
            dutyDays.insert(staff,query.size());
    }

    if(!dutyDays.isEmpty())
    {
        QList<QStandardItem *> items;
        foreach (QString staff, staffs) {
            items.append(new QStandardItem(QString::number(dutyDays.value(staff))));
        }
        if(!items.isEmpty())
        {
            itemModel->insertColumn(DUTY_COL,items);
            itemModel->setHeaderData(DUTY_COL,Qt::Horizontal,QStringLiteral("出勤数"));
        }
    }
}

void Widget::updateLateDays()
{
    if(staffs.isEmpty())
        return;

    if(!lateDays.isEmpty())
        lateDays.clear();

    if(itemModel->columnCount() > 2)
        itemModel->removeColumn(LATE_COL);

    QSqlQuery query;
    query.exec(QString("select label,COUNT(label) as tick from %1 "
                       "where time_ >= '09:00:00' AND time_ <= '12:00:00' "
                       "GROUP BY label")
               .arg(table));
    while(query.next()){
        QString label=query.value("label").toString();
        int tick=query.value("tick").toInt();
        lateDays.insert(label,tick);
    }

    if(!lateDays.isEmpty())
    {
        QList<QStandardItem *> items;
        foreach (QString staff, staffs) {
            items.append(new QStandardItem(QString::number(lateDays.value(staff))));
        }
        if(!items.isEmpty())
        {
            itemModel->insertColumn(LATE_COL,items);
            itemModel->setHeaderData(LATE_COL,Qt::Horizontal,QStringLiteral("迟到数"));  //late
        }
    }
}

void Widget::showBarChart()
{
    if(punchTicks.isEmpty() || lateDays.isEmpty() || dutyDays.isEmpty())
        return;

    QBarSet *punchSet=new QBarSet(QStringLiteral("打卡次数"));
    QBarSet *dutySet=new QBarSet(QStringLiteral("出勤天数"));
    QBarSet *lateSet=new QBarSet(QStringLiteral("迟到次数"));
    foreach (QString staff, staffs) {
        punchSet->append(punchTicks.value(staff));
        dutySet->append(dutyDays.value(staff));
        lateSet->append(lateDays.value(staff));
    }

    QBarSeries *series=new QBarSeries();
    series->append(punchSet);
    series->append(dutySet);
    series->append(lateSet);

    QChart *chart = new QChart();
    chart->setTitle(QStringLiteral("考勤统计"));
    chart->setAnimationOptions(QChart::SeriesAnimations);
    chart->addSeries(series);

    QBarCategoryAxis *axis=new QBarCategoryAxis();
    axis->append(staffs);

    chart->createDefaultAxes();
    chart->setAxisX(axis, series);
    chart->legend()->setVisible(true);
    chart->legend()->setAlignment(Qt::AlignBottom);

    QChartView *chartView = new QChartView(chart,this);
    chartView->setRenderHint(QPainter::Antialiasing);

    QHBoxLayout *layout = new QHBoxLayout;
    layout->addWidget(chartView);

    QDialog dialog;
    dialog.resize(800,600);
    dialog.setLayout(layout);
    dialog.exec();
}

void Widget::showLineChart()
{
    QModelIndex index=ui->tableView->currentIndex();
    QString label=index.sibling(index.row(),0).data().toString();
    if(!label.isEmpty())
    {
        QLineSeries *series = new QLineSeries();
        QTime baseTime=QTime(6,0,0);

        QSqlQuery query;
        query.exec(QString("select date_,time_ from %1 where label='%2' "
                           "AND time_ <= '12:00:00'")
                   .arg(table).arg(label));
        while (query.next()) {
            QDate date=query.value(0).toDate();
            QTime time=query.value(1).toTime();
            series->append(QDateTime(date).toMSecsSinceEpoch(),
                           baseTime.secsTo(time) / 60);
        }

        QChart *chart = new QChart();
        chart->setTitle(label + QStringLiteral("考勤统计"));
        chart->setAnimationOptions(QChart::SeriesAnimations);
        chart->addSeries(series);
        chart->legend()->hide();

        QDateTimeAxis *axisX = new QDateTimeAxis;
        axisX->setTickCount(20);
        axisX->setFormat("MM-dd");
        // axisX->setMin(QDateTime(baseDate));
        axisX->setTitleText("Date");
        chart->setAxisX(axisX,series);
        // chart->addAxis(axisX,Qt::AlignBottom);
        // series->attachAxis(axisX);

        QValueAxis *axisY = new QValueAxis;
        axisY->setLabelFormat("%i");
        axisY->setTitleText("Time");
        chart->setAxisY(axisY,series);
        // chart->addAxis(axisY, Qt::AlignLeft);
        // series->attachAxis(axisY);

        QChartView *chartView = new QChartView(chart,this);
        chartView->setRenderHint(QPainter::Antialiasing);

        QHBoxLayout *layout = new QHBoxLayout;
        layout->addWidget(chartView);

        QDialog dialog;
        dialog.resize(1280,600);
        dialog.setLayout(layout);
        dialog.exec();
    }
}

void Widget::showScatterChart()
{
    if(staffs.isEmpty())
        return;

    QScatterSeries *series = new QScatterSeries();
    // series->setName(staff);
    // series->setMarkerShape(QScatterSeries::MarkerShapeCircle);
    series->setMarkerSize(5.0);

    QTime baseTime=QTime(7,0,0);
    QSqlQuery query;
    query.exec(QString("select date_,time_ from %1 "
                       "where time_ <= '12:00:00'")
               .arg(table));
    while (query.next()) {
        QDate date=query.value(0).toDate();
        QTime time=query.value(1).toTime();
        series->append(QDateTime(date).toMSecsSinceEpoch(),
                       baseTime.secsTo(time) / 60);
    }

    QChart *chart = new QChart();
    chart->setTitle(QStringLiteral("出勤状况"));
    // chart->setAnimationOptions(QChart::SeriesAnimations);
    chart->addSeries(series);

    QDateTimeAxis *axisX = new QDateTimeAxis;
    axisX->setTickCount(20);
    axisX->setFormat("MM-dd");
    axisX->setTitleText("Date");
    chart->setAxisX(axisX,series);

    QValueAxis *axisY = new QValueAxis;
    axisY->setLabelFormat("%i");
    axisY->setTitleText("Time");
    chart->setAxisY(axisY,series);

    chart->legend()->hide();
    // chart->createDefaultAxes();

    QChartView *chartView = new QChartView(chart,this);
    chartView->setRenderHint(QPainter::Antialiasing);

    QHBoxLayout *layout = new QHBoxLayout;
    layout->addWidget(chartView);

    QDialog dialog;
    dialog.resize(1280,600);
    dialog.setLayout(layout);
    dialog.exec();
}
